<!--
 * @Author: fyukeeh 15849141465@163.com
 * @Date: 2025-07-24 14:57:48
 * @LastEditors: fyukeeh 15849141465@163.com
 * @LastEditTime: 2025-08-04 11:22:35
 * @FilePath: \mapbox\src\views\example\ThreeModelExample.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div style="width: 100vw; height: 100vh; position: relative;">
    <div id="map" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue';
import Map from '289-map'

const TDT_KEY = '598b1d1a4ed6d42ce765e7b6c3737c6b';
const basemaps = [
  {
    id: 'tdt-vector',
    label: '天地图矢量',
    thumb: 'https://api.tianditu.gov.cn/img/vec.png',
  },
  {
    id: 'tdt-image',
    label: '天地图影像',
    thumb: 'https://api.tianditu.gov.cn/img/img.png',
  },
  {
    id: 'tdt-terrain',
    label: '天地图地形',
    thumb: 'https://api.tianditu.gov.cn/img/ter.png',
  },
];

function addTdtSourceAndLayer(map, item, visible) {
  const tiles = [`https://t0.tianditu.gov.cn/DataServer?T=${item.id === 'tdt-vector' ? 'vec_w' : item.id === 'tdt-image' ? 'img_w' : 'ter_w'}&x={x}&y={y}&l={z}&tk=${TDT_KEY}`];
  if (!map.getSource(item.id)) {
    map.addSource(item.id, {
      type: 'raster',
      tiles,
      tileSize: 256,
      attribution: '© 天地图'
    });
  }
  if (!map.getLayer(item.id + '-layer')) {
    map.addLayer({
      id: item.id + '-layer',
      type: 'raster',
      source: item.id,
      layout: { visibility: visible ? 'visible' : 'none' }
    }, map.getStyle().layers?.[0]?.id);
  }
}

let map;

function ensureThreeModelLayer() {
  // 如果已存在three-model图层，先移除再添加，避免重复或被遮挡
  if (map.getLayer && map.getLayer('three-model')) {
    try { map.removeLayer('three-model'); } catch(e) {}
  }
  const modelLoader = new Map.Graphic.ThreeModelLoader({
    modelUrl: '/GLTF/34M_17/34M_17.gltf',
    modelOrigin: [116.40, 39.90],
    modelAltitude: 0,
    scaling: 10000
  });
  map.addLayer(modelLoader.getCustomLayer(map));
  // 确保在最顶层
  try { map.moveLayer('three-model'); } catch(e) {}
}

onMounted(() => {
  map = new Map('map', {
    style: {
      version: 8,
      sources: {},
      layers: [],
    },
    scene: {
      center: {
        lng: 116.40,
        lat: 39.90,
        pitch: 0
      },
      zoom: 2
    },
    controller: ['showZoom', 'showCompass', 'globe', 'visualizePitch', 'basemapSwitcher'],
    basemaps,
    attributionControl: true,
    type: 'globe'
  });

  map.on('load', () => {
    basemaps.forEach((item, idx) => {
      addTdtSourceAndLayer(map, item, idx === 0);
    });
    ensureThreeModelLayer();
  });

  map.on('style.load', () => {
    ensureThreeModelLayer();
  });
});
</script> 